using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Web;

namespace GottaGottaScrum.Models
{ 
    public class WorkItemODataRepository : IWorkItemRepository
    {
			ServiceReference1.TFSData context;

			public WorkItemODataRepository()
			{
				context = new ServiceReference1.TFSData(new System.Uri("http://localhost/ODataTFS.Web/TFS29/"));
				context.SendingRequest += (s, e) =>
{
	var credentials = string.Format(System.Globalization.CultureInfo.InvariantCulture, @"{0}\{1}:{2}", "snd", "trip42_cp", "abcdef");

	e.RequestHeaders.Add("Authorization", "Basic " + Convert.ToBase64String(new System.Text.ASCIIEncoding().GetBytes(credentials)));
};
				System.Net.ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => { return true; };

			}


        public IQueryable<WorkItem> All
        {get {
					List<WorkItem> asdf =  new List<WorkItem>();
					foreach (ServiceReference1.WorkItem tmp in context.WorkItems)
					{
						asdf.Add(new WorkItem(tmp));
					}
					return asdf.AsQueryable();
				}
        }

        public IQueryable<WorkItem> AllIncluding(params Expression<Func<WorkItem, object>>[] includeProperties)
        {
					throw new System.NotImplementedException();
						//IQueryable<ServiceReference1.WorkItem> query = context.WorkItems.AsQueryable();
						//foreach (var includeProperty in includeProperties) {
						//    query = query.Include(includeProperty);
						//}
						//return query;
        }

        public WorkItem Find(int id)
        {
					foreach (ServiceReference1.WorkItem tmp in context.WorkItems)
					{
						if (tmp.Id == id)
						{
							return new WorkItem(tmp);
						}
					}
					throw new System.ArgumentException();
        }

        public void InsertOrUpdate(WorkItem workitem)
        {
            if (workitem.Id == default(int)) {
                // New entity
							ServiceReference1.WorkItem tmp = (ServiceReference1.WorkItem)workitem;
							tmp.Project = context.Projects.First<ServiceReference1.Project>().Name;
							tmp.Type = "Work Item";
							context.AddToWorkItems(tmp);
            } else {
							ServiceReference1.WorkItem tmp = (ServiceReference1.WorkItem)workitem;
							context.AttachTo("WorkItems", tmp);
							context.UpdateObject(tmp);
            }
        }

        public void Delete(int id)
        {
					context.DeleteObject(Find(id));
				}

				public void Save()
        {
					context.SaveChanges();
        }
    }
}